/*
 *  SSChartLegendView.m
 *  MESLib
 * 
 * Copyright 2003-2009 Starline Software Ltd
 * 
 * This file is part of MESLib.
 * 
 * MESLib is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * MESLib is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with MESLib. If not, see <http://www.gnu.org/licenses/>.
 */
//  Created by Tobias Haughton on Sun Apr 20 2003.
//

#import "SSChartLegendView.h"
#import "SSCatalystDocument.h"

@implementation SSChartLegendView

- (id)initWithFrame:(NSRect)frame {
   self = [super initWithFrame:frame];
   if (self) {

   }
   return self;
}

- (void)awakeFromNib
{
   NSFont *font = [NSFont fontWithName:@"Helvetica" size:10];

   titleString = [[NSAttributedString alloc] initWithString:@"Title:"
                                                 attributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:10],
                                                    NSFontAttributeName, nil, nil]];
   authorString = [[NSAttributedString alloc] initWithString:@"Author:"
                                                  attributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:10],
                                                     NSFontAttributeName, nil, nil]];
   dateString = [[NSAttributedString alloc] initWithString:@"Date:"
                                                attributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:10],
                                                   NSFontAttributeName, nil, nil]];
   estimatedTimeString = [[NSMutableAttributedString alloc] initWithString:@"e = estimate"
                                                attributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:10],
                                                   NSFontAttributeName, nil, nil]];

   //create the fields
   titleField = [[[NSTextField alloc] initWithFrame:NSMakeRect(([authorString size].width + (SSLegendViewDistanceBetweenObjects * 2)), SSLegendViewRow1YPos, 150, SSEventFieldHeight)] autorelease];
   [[titleField cell] setBordered:NO];
   [[titleField cell] setFont:font];
   [titleField setSelectable:NO];
   [titleField setDelegate:self];
   [titleField setStringValue:[theDocument title]];
   [titleField setTag:0];
   [self addSubview:titleField];

   authorField = [[[NSTextField alloc] initWithFrame:NSMakeRect(([authorString size].width + (SSLegendViewDistanceBetweenObjects * 2)), SSLegendViewRow2YPos, 150, SSEventFieldHeight)] autorelease];
   [[authorField cell] setBordered:NO];
   [[authorField cell] setFont:font];
   [authorField setSelectable:NO];
   [authorField setDelegate:self];
   [authorField setStringValue:[theDocument author]];
   [authorField setTag:1];
   [self addSubview:authorField];

   NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] initWithDateFormat:[NSString stringWithFormat:@"%@:%@:%@",
      @"%Y", @"%m", @"%d"] allowNaturalLanguage:NO] autorelease];
   dateField = [[[NSTextField alloc] initWithFrame:NSMakeRect((NSMaxX([titleField frame]) + SSLegendViewDistanceBetweenObjects + [dateString size].width + SSLegendViewDistanceBetweenObjects), SSLegendViewRow1YPos, 100, SSEventFieldHeight)] autorelease];
   [[dateField cell] setBordered:NO];
   [[dateField cell] setFont:font];
   [dateField setSelectable:NO];
   [dateField setDelegate:self];
   [dateField setFormatter:dateFormatter];
   [dateField setObjectValue:[theDocument chartDate]];
   [dateField setTag:10];
   [self addSubview:dateField];

   whiteRect = NSMakeRect((NSMaxX([dateField frame]) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow1YPos, SSEventFieldHeight, SSEventFieldHeight);
   whiteField = [[[NSTextField alloc] initWithFrame:NSMakeRect((NSMaxX(whiteRect) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow1YPos, 100, SSEventFieldHeight)] autorelease];
   [[whiteField cell] setBordered:NO];
   [[whiteField cell] setFont:font];
   [whiteField setSelectable:NO];
   [whiteField setDelegate:self];
   [whiteField setStringValue:[theDocument whiteColorDesignation]];
   [whiteField setTag:2];
   [self addSubview:whiteField];

   yellowRect = NSMakeRect((NSMaxX([dateField frame]) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow2YPos, SSEventFieldHeight, SSEventFieldHeight);
   yellowField = [[[NSTextField alloc] initWithFrame:NSMakeRect((NSMaxX(yellowRect) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow2YPos, 100, SSEventFieldHeight)] autorelease];
   [[yellowField cell] setBordered:NO];
   [[yellowField cell] setFont:font];
   [yellowField setSelectable:NO];
   [yellowField setDelegate:self];
   [yellowField setStringValue:[theDocument yellowColorDesignation]];
   [yellowField setTag:3];
   [self addSubview:yellowField];

   greenRect = NSMakeRect((NSMaxX([whiteField frame]) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow1YPos, SSEventFieldHeight, SSEventFieldHeight);
   greenField = [[[NSTextField alloc] initWithFrame:NSMakeRect((NSMaxX(greenRect) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow1YPos, 100, SSEventFieldHeight)] autorelease];
   [[greenField cell] setBordered:NO];
   [[greenField cell] setFont:font];
   [greenField setSelectable:NO];
   [greenField setDelegate:self];
   [greenField setStringValue:[theDocument greenColorDesignation]];
   [greenField setTag:4];
   [self addSubview:greenField];

   lightBlueRect = NSMakeRect((NSMaxX([whiteField frame]) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow2YPos, SSEventFieldHeight, SSEventFieldHeight);
   lightBlueField = [[[NSTextField alloc] initWithFrame:NSMakeRect((NSMaxX(lightBlueRect) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow2YPos, 100, SSEventFieldHeight)] autorelease];
   [[lightBlueField cell] setBordered:NO];
   [[lightBlueField cell] setFont:font];
   [lightBlueField setSelectable:NO];
   [lightBlueField setDelegate:self];
   [lightBlueField setStringValue:[theDocument lightBlueColorDesignation]];
   [lightBlueField setTag:5];
   [self addSubview:lightBlueField];

   blueRect = NSMakeRect((NSMaxX([greenField frame]) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow1YPos, SSEventFieldHeight, SSEventFieldHeight);
   blueField = [[[NSTextField alloc] initWithFrame:NSMakeRect((NSMaxX(blueRect) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow1YPos, 100, SSEventFieldHeight)] autorelease];
   [[blueField cell] setBordered:NO];
   [[blueField cell] setFont:font];
   [blueField setSelectable:NO];
   [blueField setDelegate:self];
   [blueField setStringValue:[theDocument blueColorDesignation]];
   [blueField setTag:6];
   [self addSubview:blueField];

   purpleRect = NSMakeRect((NSMaxX([greenField frame]) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow2YPos, SSEventFieldHeight, SSEventFieldHeight);
   purpleField = [[[NSTextField alloc] initWithFrame:NSMakeRect((NSMaxX(purpleRect) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow2YPos, 100, SSEventFieldHeight)] autorelease];
   [[purpleField cell] setBordered:NO];
   [[purpleField cell] setFont:font];
   [purpleField setSelectable:NO];
   [purpleField setDelegate:self];
   [purpleField setStringValue:[theDocument purpleColorDesignation]];
   [purpleField setTag:7];
   [self addSubview:purpleField];

   orangeRect = NSMakeRect((NSMaxX([blueField frame]) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow1YPos, SSEventFieldHeight, SSEventFieldHeight);
   orangeField = [[[NSTextField alloc] initWithFrame:NSMakeRect((NSMaxX(orangeRect) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow1YPos, 100, SSEventFieldHeight)] autorelease];
   [[orangeField cell] setBordered:NO];
   [[orangeField cell] setFont:font];
   [orangeField setSelectable:NO];
   [orangeField setDelegate:self];
   [orangeField setStringValue:[theDocument orangeColorDesignation]];
   [orangeField setTag:8];
   [self addSubview:orangeField];

   redRect = NSMakeRect((NSMaxX([blueField frame]) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow2YPos, SSEventFieldHeight, SSEventFieldHeight);
   redField = [[[NSTextField alloc] initWithFrame:NSMakeRect((NSMaxX(redRect) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow2YPos, 100, SSEventFieldHeight)] autorelease];
   [[redField cell] setBordered:NO];
   [[redField cell] setFont:font];
   [redField setSelectable:NO];
   [redField setDelegate:self];
   [redField setStringValue:[theDocument redColorDesignation]];
   [redField setTag:9];
   [self addSubview:redField];

   titleStringDrawPoint = NSMakePoint(SSLegendViewDistanceBetweenObjects, SSLegendViewRow1YPos);
   authorStringDrawPoint = NSMakePoint(SSLegendViewDistanceBetweenObjects, SSLegendViewRow2YPos);
   dateStringDrawPoint = NSMakePoint((NSMaxX([titleField frame]) + SSLegendViewDistanceBetweenObjects), SSLegendViewRow1YPos);
   estimatedStringDrawPoint = NSMakePoint((NSMaxX([titleField frame]) + SSLegendViewDistanceBetweenObjects), (SSLegendViewRow2YPos - 5));

   [[NSNotificationCenter defaultCenter] addObserver:self
          selector:@selector(updateFieldValues)
              name:@"SSMatrixPropertyChanged"
            object:theDocument];
}

- (void)drawRect:(NSRect)rect {
   [[NSColor whiteColor] set];
   [NSBezierPath fillRect:[self bounds]];

   [[NSColor blackColor] set];

   //draw the strings
   [titleString drawAtPoint:titleStringDrawPoint];
   [authorString drawAtPoint:authorStringDrawPoint];
   [dateString drawAtPoint:dateStringDrawPoint];
   [estimatedTimeString drawAtPoint:estimatedStringDrawPoint];

   //draw the colors
   [NSBezierPath strokeRect:whiteRect];
   [NSBezierPath strokeRect:yellowRect];
   [NSBezierPath strokeRect:greenRect];
   [NSBezierPath strokeRect:lightBlueRect];
   [NSBezierPath strokeRect:blueRect];
   [NSBezierPath strokeRect:purpleRect];
   [NSBezierPath strokeRect:orangeRect];
   [NSBezierPath strokeRect:redRect];

   [[NSColor whiteColor] set];
   [NSBezierPath fillRect:whiteRect];
   
   [SSYellowColor set];
   [NSBezierPath fillRect:yellowRect];

   [SSGreenColor set];
   [NSBezierPath fillRect:greenRect];

   [SSLightBlueColor set];
   [NSBezierPath fillRect:lightBlueRect];

   [SSBlueColor set];
   [NSBezierPath fillRect:blueRect];

   [SSPurpleColor set];
   [NSBezierPath fillRect:purpleRect];

   [SSOrangeColor set];
   [NSBezierPath fillRect:orangeRect];

   [SSRedColor set];
   [NSBezierPath fillRect:redRect];
}

//***********************************mouse events
- (void)mouseDown:(NSEvent *)theEvent
{
   NSPoint converted = [self convertPoint:[theEvent locationInWindow] fromView:nil];
   
   if([self selectedField]) { //stop the currently selected text field from being edited
      [self setSelectedField:nil];
   }

   if([theEvent clickCount] == 2) { //if user double clicks see if it is above one of our text fields and if so allow editing
      [self allowEditingInFieldAtPoint:[theEvent locationInWindow]];
   } else {
      //see if the user has clicked in one of the color boxes and if so get the EBs to set their color
      [self setEBLabelsIfWithinColorBox:converted];
   }
}

- (void)setEBLabelsIfWithinColorBox:(NSPoint)point
{
   if([self pointIsWithinRect:point rect:whiteRect]) {
      //click is within white rect
      [[[NSDocumentController sharedDocumentController] currentDocument] setAllSelectedEventsWithLabel:[NSNumber numberWithInt:SSWhiteLabelType]];
   } else if([self pointIsWithinRect:point rect:yellowRect]) {
      //click is within yellow rect
      [[[NSDocumentController sharedDocumentController] currentDocument] setAllSelectedEventsWithLabel:[NSNumber numberWithInt:SSYellowLabelType]];
   } else if([self pointIsWithinRect:point rect:greenRect]) {
      //click is within green rect
      [[[NSDocumentController sharedDocumentController] currentDocument] setAllSelectedEventsWithLabel:[NSNumber numberWithInt:SSGreenLabelType]];
   } else if([self pointIsWithinRect:point rect:lightBlueRect]) {
      //click is within light blue rect
      [[[NSDocumentController sharedDocumentController] currentDocument] setAllSelectedEventsWithLabel:[NSNumber numberWithInt:SSLightBlueLabelType]];
   } else if([self pointIsWithinRect:point rect:blueRect]) {
      //click is within blue rect
      [[[NSDocumentController sharedDocumentController] currentDocument] setAllSelectedEventsWithLabel:[NSNumber numberWithInt:SSBlueLabelType]];
   } else if([self pointIsWithinRect:point rect:purpleRect]) {
      //click is within purple rect
      [[[NSDocumentController sharedDocumentController] currentDocument] setAllSelectedEventsWithLabel:[NSNumber numberWithInt:SSPurpleLabelType]];
   } else if([self pointIsWithinRect:point rect:orangeRect]) {
      //click is within orange rect
      [[[NSDocumentController sharedDocumentController] currentDocument] setAllSelectedEventsWithLabel:[NSNumber numberWithInt:SSOrangeLabelType]];
   } else if([self pointIsWithinRect:point rect:redRect]) {
      //click is within red rect
      [[[NSDocumentController sharedDocumentController] currentDocument] setAllSelectedEventsWithLabel:[NSNumber numberWithInt:SSRedLabelType]];
   }
}

//***********************************
- (BOOL)pointIsWithinRect:(NSPoint)point rect:(NSRect)rect
{
   if(point.x > NSMinX(rect) && point.x < NSMaxX(rect)) {
      //it is within the x range of this rect
      if(point.y > NSMinY(rect) && point.y < NSMaxY(rect)) {
         //it is within this rect
         return YES;
      }
   }
   return NO;
}

- (void)allowEditingInFieldAtPoint:(NSPoint)point
{
   NSEnumerator *enumerator = [[self subviews] objectEnumerator];
   id anObject;
   point = [self convertPoint:point fromView:nil];

   while(anObject = [enumerator nextObject]) {
      if(point.x > NSMinX([anObject frame]) && point.x < NSMaxX([anObject frame])) {
         //it is within the x range of this object
         if(point.y > NSMinY([anObject frame]) && point.y < NSMaxY([anObject frame])) {
            //double click was above this field
            [self setSelectedField:anObject];
            break;
         }
      }
   }
}

- (void)setSelectedField:(NSTextField *)field
{
   //deselect the selected field
   [[self selectedField] setSelectable:NO];
   [[self selectedField] setBordered:NO];
   [[self window] makeFirstResponder:[self window]];

   selectedField = field;

   if(selectedField) {
      //if a field has been passed select it
      [field setEditable:YES];
      [field selectText:self];
      [field setBordered:YES];
      [[self window] makeFirstResponder:field];
   }
}

- (NSTextField *)selectedField
{
   return selectedField;
}

- (void)selectNextField
{
   //select the next field based on the current fields tag
   switch([[self selectedField] tag]) {
      case 0:[self setSelectedField:authorField];
         break;
      case 1:[self setSelectedField:dateField];
         break;
      case 10:[self setSelectedField:whiteField];
         break;
      case 2:[self setSelectedField:yellowField];
         break;
      case 3:[self setSelectedField:greenField];
         break;
      case 4:[self setSelectedField:lightBlueField];
         break;
      case 5:[self setSelectedField:blueField];
         break;
      case 6:[self setSelectedField:purpleField];
         break;
      case 7:[self setSelectedField:orangeField];
         break;
      case 8:[self setSelectedField:redField];
         break;
      default:[self setSelectedField:titleField];
         break;
   }
}

//***********************************
- (void)controlTextDidEndEditing:(NSNotification *)note
{
   //called when a text field stops editing
   switch([[note object] tag]) {
      case 0:
         if(![[[note object] stringValue] isEqualToString:[theDocument title]]) { //if it hasn't changed don't set the same value
            [theDocument setTitle:[[note object] stringValue]];
         }
         break;
      case 1:
         if(![[[note object] stringValue] isEqualToString:[theDocument author]]) { //if it hasn't changed don't set the same value
            [theDocument setAuthor:[[note object] stringValue]];
         }
         break;
      case 2:
         if(![[[note object] stringValue] isEqualToString:[theDocument whiteColorDesignation]]) { //if it hasn't changed don't set the same value
            [theDocument setWhiteColorDesignation:[[note object] stringValue]];
         }
         break;
      case 3:
         if(![[[note object] stringValue] isEqualToString:[theDocument yellowColorDesignation]]) { //if it hasn't changed don't set the same value
            [theDocument setYellowColorDesignation:[[note object] stringValue]];
         }
         break;
      case 4:
         if(![[[note object] stringValue] isEqualToString:[theDocument greenColorDesignation]]) { //if it hasn't changed don't set the same value
            [theDocument setGreenColorDesignation:[[note object] stringValue]];
         }
         break;
      case 5:
         if(![[[note object] stringValue] isEqualToString:[theDocument lightBlueColorDesignation]]) { //if it hasn't changed don't set the same value
            [theDocument setLightBlueColorDesignation:[[note object] stringValue]];
         }
         break;
      case 6:
         if(![[[note object] stringValue] isEqualToString:[theDocument blueColorDesignation]]) { //if it hasn't changed don't set the same value
            [theDocument setBlueColorDesignation:[[note object] stringValue]];
         }
         break;
      case 7:
         if(![[[note object] stringValue] isEqualToString:[theDocument purpleColorDesignation]]) { //if it hasn't changed don't set the same value
            [theDocument setPurpleColorDesignation:[[note object] stringValue]];
         }
         break;
      case 8:
         if(![[[note object] stringValue] isEqualToString:[theDocument orangeColorDesignation]]) { //if it hasn't changed don't set the same value
            [theDocument setOrangeColorDesignation:[[note object] stringValue]];
         }
         break;
      case 9:
         if(![[[note object] stringValue] isEqualToString:[theDocument redColorDesignation]]) { //if it hasn't changed don't set the same value
            [theDocument setRedColorDesignation:[[note object] stringValue]];
         }
         break;
      case 10:
         if(![(NSCalendarDate *)[[note object] objectValue] isEqualTo:(NSCalendarDate *)[theDocument chartDate]]) { //if it hasn't changed don't set the same value
            [theDocument setChartDate:[[note object] objectValue]];
         }
         break;
      default:
         break;
   }   
}

- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector
{
   if(commandSelector == @selector(insertTab:)) {
      //user pressed tab
      [self selectNextField];
      return YES;
   } else {
      if(commandSelector == @selector(insertNewline:)) {
         //user pressed return end editing
         [self setSelectedField:nil];
         return YES;
      } else {
         return NO;
      }
   }
}

- (void)updateFieldValues
{
   [titleField setStringValue:[theDocument title]];
   [authorField setStringValue:[theDocument author]];
   [dateField setObjectValue:[theDocument chartDate]];
   [whiteField setStringValue:[theDocument whiteColorDesignation]];
   [yellowField setStringValue:[theDocument yellowColorDesignation]];
   [greenField setStringValue:[theDocument greenColorDesignation]];
   [lightBlueField setStringValue:[theDocument lightBlueColorDesignation]];
   [blueField setStringValue:[theDocument blueColorDesignation]];
   [purpleField setStringValue:[theDocument purpleColorDesignation]];
   [orangeField setStringValue:[theDocument orangeColorDesignation]];
   [redField setStringValue:[theDocument redColorDesignation]];
}

//***********************************
- (BOOL)isFlipped
{
   //changes the coordinate system so 0,0 is in the top left
   return YES;
}

- (BOOL)isOpaque
{
   // State that the view is opaque for optimization purposes.
   return YES;
}
//***********************************

- (void)dealloc
{
   [[NSNotificationCenter defaultCenter] removeObserver:self];
   
   [titleString release];
   [authorString release];
   [dateString release];
   [estimatedTimeString release];
   [super dealloc];
}

@end
